package com.example.mymenu.manager;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class DbManager {

    private MyDbHelper myDbHelper;
    private SQLiteDatabase sqLiteDatabase;

    public DbManager(Context context){
        myDbHelper = new MyDbHelper(context,"MyDatabase.db",null,1);
        sqLiteDatabase = myDbHelper.getWritableDatabase();
    }

    //插入数据
    public void insert(String table, String nullColumnHack, ContentValues values){
        sqLiteDatabase.insert(table,nullColumnHack,values);
    }

    //查询数据
    public Cursor query(String table,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy){
        Cursor cursor = sqLiteDatabase.query(table,columns,selection,selectionArgs,groupBy,having,orderBy);
        return cursor;
    }

    //查询表中所有数据行数
    public Integer queryColumnsNumber(String table){
        Cursor cursor = sqLiteDatabase.query(table,null,null,null,null,null,null);
        return cursor.getCount();
    }

    //关闭数据库连接
    public void close(){
        sqLiteDatabase.close();
    }


    private class MyDbHelper extends SQLiteOpenHelper {
        public MyDbHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {

            sqLiteDatabase.execSQL("create table menu(menu_id varchar(10) primary key,name varchar(20),time varchar(20),content varchar(100),marterial varchar(100)," +
                    "pcontent varchar(500),function varchar(10),pic varchar(500))");
        }

        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

        }
    }
}
